package edu.sctu.practice.class02.hujie.online_classes_practice.imooc.Java_XMLRead.DOM;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

/**
 * Created by hp on 2016/3/7.
 */
public class DOMtest {
    public DocumentBuilder getDocumentBuilder() {
        //创建一个DocumentBuilderFactory的对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//返回的是document的类型的值
        //创建DocumentBuilder对象
        DocumentBuilder db = null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return db;
    }

    public void xmlParser() {
        try {
            //通过documentBuilder对象的parser方法加载books.xml文件到当前项目下
            Document document = getDocumentBuilder().parse("src\\main\\java\\edu\\sctu\\practice\\class02\\hujie\\online_classes_practice\\imooc\\Java_XMLRead\\books.xml");
            //获取所有book节点的集合
            NodeList booklist = document.getElementsByTagName("book");
            System.out.println("一共有" + booklist.getLength() + "本书");
            //遍历每一个节点
            for (int i = 0; i < booklist.getLength(); i++) {
                //通过item(i)方法 获取一个book
                Node book = booklist.item(i);
                //获取book节点的所有属性集合
                NamedNodeMap attrs = book.getAttributes();
                System.out.println("第" + (i + 1) + "本书共有" + attrs.getLength() + "个属性");
                for (int j = 0; j < attrs.getLength(); j++) {
                    System.out.println("********下面开始遍历第" + (i + 1) + "本书的内容********");
                    Node attr = attrs.item(j);
                    attr.getNodeName();
                    System.out.println("属性名" + attr.getNodeName());
                    System.out.println("属性值" + attr.getNodeValue());
                    //解析book节点的子节点
                    NodeList childNode = book.getChildNodes();
                    //遍历childNode获取每个节点的节点名和节点值
                    System.out.println("第" + (i + 1) + "本书共有" + childNode.getLength() + "个子节点");
                    for (int k = 0; k < childNode.getLength(); k++) {
                        //区分出text类型node以及element类型的node
                        if (childNode.item(k).getNodeType() == Node.ELEMENT_NODE) {
                            //获取element类型节点的节点名
                            System.out.print("第" + (k + 1) + "个节点名是：" + childNode.item(k).getNodeName());
                            //获取element类型节点的节点值
//                            System.out.println("节点值是："+childNode.item(k).getFirstChild().getNodeValue());
                            System.out.println("节点值是：" + childNode.item(k).getTextContent());//这个会获取所有的值
                        }
                    }
                }
                System.out.println("********下面结束遍历第" + (i + 1) + "本书的内容********");
            }
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //生成xml
    public void createXML() {
        DocumentBuilder db = getDocumentBuilder();
        Document document = db.newDocument();
        document.setXmlStandalone(true);//将不必要的文件属性去掉
        Element bookstore = document.createElement("bookstore");
        //向bookStore根节点添加子节点book

        Element book = document.createElement("book");
        book.setAttribute("id", "1");
        Element name = document.createElement("name");
        book.appendChild(name);
        name.setTextContent("小王子");
        Element author = document.createElement("author");
        book.appendChild(author);
        author.setTextContent("安托万·德·圣·埃克苏佩");
        Element year = document.createElement("year");
        book.appendChild(year);
        year.setTextContent("1942");
        //将book节点添加到bookstore根节点中
        bookstore.appendChild(book);
        //将bookstore节点(已经包含了book)添加到dom树中
        document.appendChild(bookstore);
        //
        TransformerFactory tff = TransformerFactory.newInstance();
        try {
            Transformer tf = tff.newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.transform(new DOMSource(document), new StreamResult(new File("src\\main\\java\\edu\\sctu\\practice\\class02\\hujie\\online_classes_practice\\imooc\\Java_XMLRead\\books1.xml")));
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    /*
    * 主程序入口
    * */
    public static void main(String[] args) {
        //创建DOMtest对象
        DOMtest test = new DOMtest();
        //条用解析方法，解析xml文件
//        test.xmlParser();
        test.createXML();//会覆盖原来的文件
    }
}
